package nba2kmodtool.filedesc;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.List;

import nba2kmodtool.util.ByteFileReader;

class N2kModelObjFileExporter {
	private static final boolean IS_DEBUG = BaseIffFile.IS_DEBUG;

	protected BaseIffFile iff;
	protected File file;

	protected N2kModelObjFileExporter(BaseIffFile iff) {
		this.iff = iff;
		this.file = iff.file;
	}

	public void exportModelToOBJFile(File outfile, N2k3DModelPart[] models) throws IOException {
		ByteFileReader in = new ByteFileReader(file, "r");
		PrintWriter out = new PrintWriter(new FileWriter(outfile));
		out.print("# This file uses centimeters as units for non-parametric coordinates.");
		out.print((char) 0x0A);
		out.print((char) 0x0A);
		int num = models.length;
		int partNum = 0;
		for (int i = 0; i < num; i++) {
			N2k3DModelPart part = models[i];
			if (part == null || part.childNum < 1) {
				continue;
			}
			List<FloatBuffer> vertexs = iff.getChildModelVertets(part, in);
			List<IntBuffer> faces = iff.resolve3DModelFaceData(part, in, false);
			for (int j = 0; j < part.childNum; j++) {
				partNum++;
				String partName = String.format("m%d_%d_m", i, j);
				out.print("g default");
				out.print((char) 0x0A);
				FloatBuffer vertBuf = vertexs.get(j * 2);
				FloatBuffer uvnBuf = vertexs.get(j * 2 + 1);
				IntBuffer fcBuf = faces.get(j);
				int vertNum = vertBuf.array().length / 3;
				int faceNum = fcBuf.array().length / 3;
				//write vertex position
				for (int n = 0; n < vertNum; n++) {
					StringBuffer str = new StringBuffer("v");
					str.append(" ").append(vertBuf.get());
					str.append(" ").append(vertBuf.get());
					str.append(" ").append(vertBuf.get());
					out.print(str.toString());
					out.print((char) 0x0A);
				}
				//write uv position
				for (int n = 0; n < vertNum; n++) {
					StringBuffer str = new StringBuffer("vt");
					str.append(" ").append(uvnBuf.get());
					str.append(" ").append(uvnBuf.get());
					out.print(str.toString());
					out.print((char) 0x0A);
				}
				//write faces
				out.print("g " + partName);
				out.print((char) 0x0A);
				for (int n = 0; n < faceNum; n++) {
					StringBuffer str = new StringBuffer("f");
					short a = (short) (fcBuf.get() + 1);
					short b = (short) (fcBuf.get() + 1);
					short c = (short) (fcBuf.get() + 1);
					str.append(" ").append(a).append("/").append(a);
					str.append(" ").append(b).append("/").append(b);
					str.append(" ").append(c).append("/").append(c);
					out.print(str.toString());
					out.print((char) 0x0A);
				}
			}
		}
		//		long len = out.getFilePointer();
		//		//fix part num
		//		out.seek(0x04);
		//		out.writeInt(Integer.reverseBytes(partNum));
		//		out.setLength(len);
		out.flush();
		in.close();
		out.close();
	}
}
